﻿#include <stdio.h>//标准输入输出
#include <stdlib.h>//函数库
#include <string.h>//字符串操作
#include <dirent.h> //目录名获取配合DIR
#include <assert.h>//断言
#include <sys/stat.h>//文件状态操作
#include <sys/types.h>//获取pid等
#include <unistd.h>//文件操作
#include <fcntl.h> //文件控制操作
#include <sys/types.h> //获取pid等
#include <sys/wait.h> //等待子进程结束
#include <time.h> //时间获取
#include <sys/ipc.h> //进程通信
#include <sys/msg.h> //消息队列
#include <sys/shm.h> //共享内存
#include <signal.h> //信号处理
#include <pthread.h> //线程
#include <sys/types.h>//获取pid等
#include <sys/socket.h>//socket
#include <netinet/in.h>//socket
#include <arpa/inet.h>//socket
#include <sys/epoll.h>//epoll


//epoll学习
int main(int argc, char *argv[])
{
	int sock = 0;
	int ret = 0;
	int listenfd = 0;
	struct sockaddr_in addr;
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == -1) {
		perror("socket");
		exit(-1);
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(6917);//-----------------------------------------------------------------------------------------
	addr.sin_addr.s_addr = inet_addr("192.168.48.128");

	ret = bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr));
	if (ret == -1)
	{
		perror("bind");
		exit(-1);
	}
	listen(sock, 5);


	//创建epoll
	int epollfd = 0;
	epollfd = epoll_create1(0);
	if (epollfd == -1) {
		perror("epoll_create1");
		exit(EXIT_FAILURE);
	}

	//添加监听事件
	struct epoll_event ev;
	memset(&ev, 0, sizeof(ev));
	ev.events = EPOLLIN;
	ev.data.fd = sock;
	ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, sock, &ev);
	if (ret == -1) {
		perror("epoll_ctl");
		exit(EXIT_FAILURE);
	}

	//监控套接字集合 
	int nfds = 0;
	struct epoll_event events[10];
	while (1) {
		nfds = epoll_wait(epollfd, events, 10, 0);
		if (nfds == -1) {
			perror("epoll_wait");
			exit(EXIT_FAILURE);
		}
		for (int i = 0; i < nfds; i++) {
			if (events[i].data.fd == sock) {//如果是监听套接字
				struct sockaddr_in client_addr;
				socklen_t len = sizeof(client_addr);
				int listenfd = accept(sock, (struct sockaddr*)&client_addr, &len);
				if (listenfd == -1) {
					perror("accept");
					exit(EXIT_FAILURE);
				}
				//添加客户端通信套接字进入集合
				struct epoll_event ev;
				memset(&ev, 0, sizeof(ev));
				ev.events = EPOLLIN;
				ev.data.fd = listenfd;
				ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev);
				if (ret == -1) {
					perror("epoll_ctl");
					exit(EXIT_FAILURE);
				}
			}
			else {//如果是通信套接字
				char buf[1024] = { 0 };
				ret = recv(events[i].data.fd, buf, sizeof(buf), 0);
				printf("收到的buf是：%s\n", buf);
				if (ret == -1) {
					perror("recv");
				}
				else if (ret == 0) {
					printf("客户端关闭\n");
					ret = epoll_ctl(epollfd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
					close(events[i].data.fd);
					continue;

				}
			}
		}
	}
}